package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmChannelDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmChannelService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 查询所有的频道
     * @return
     */
    @Override
    public ResponseResult findAll() {
        return ResponseResult.okResult(this.list());
    }

    /**
     * 分页查询所有的频道
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findPage(WmChannelDto dto) {

        // 校验参数
        dto.checkParam();

        // 分页查询
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmChannel> queryWrapper = Wrappers.lambdaQuery(WmChannel.class)
                .like(StringUtils.isNotBlank(dto.getName()), WmChannel::getName, dto.getName())
                .eq(dto.getStatus()!=null, WmChannel::getStatus, dto.getStatus())
                .orderByDesc(WmChannel::getCreatedTime);
        this.page(page, queryWrapper);

        // 分装结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());

        return pageResponseResult;
    }

    /**
     * 添加频道数据
     *
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult saveWmChannel(WmChannel wmChannel) {

        // 校验参数
        if (wmChannel == null || StringUtils.isBlank(wmChannel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 名称不能重复
        WmChannel channel = this.getOne(Wrappers.lambdaQuery(WmChannel.class)
                .eq(WmChannel::getName, wmChannel.getName()));
        if (channel != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"频道名称不能重复");
        }

        // 保存数据

        wmChannel.setIsDefault(true);
        wmChannel.setCreatedTime(new Date());

        this.save(wmChannel);

        return ResponseResult.okResult("添加频道成功");
    }

    /**
     * 根据id修改频道数据
     *
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult updateWmChannel(WmChannel wmChannel) {
        // 校验参数
        if (wmChannel == null || StringUtils.isBlank(wmChannel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据Id查询数据
        WmChannel channel = this.getById(wmChannel.getId());

        if (StringUtils.isBlank(wmChannel.getDescription())) {
            wmChannel.setDescription(channel.getDescription());
        }

        if (wmChannel.getOrd() != null) {
            wmChannel.setOrd(channel.getOrd());
        }

        // 排除名称重复的数据
        List<WmChannel> channelList = this.list();
        List<String> nameList = channelList.stream()
                .filter(param -> !param.getId().equals(wmChannel.getId()))
                .map(WmChannel::getName)
                .collect(Collectors.toList());
        if (nameList.contains(wmChannel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"修改的频道名称不能重复!");
        }

        // 如果禁用数据，需要验证当前频道是否被引用了
        if (!wmChannel.getStatus()) {
            List<WmNews> list = wmNewsMapper.selectList(Wrappers.lambdaQuery(WmNews.class)
                    .eq(WmNews::getChannelId, wmChannel.getId()));

            if (list != null && list.size() > 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"此频道被引用，不能禁用");
            }
        }

        // 修改频道数据
        this.updateById(wmChannel);

        return ResponseResult.okResult("修改成功");
    }

    /**
     * 根据Id删除频道数据
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteById(Integer id) {

        // 根据当前id查询频道数据
        WmChannel wmchannel = this.getById(id);
        if (wmchannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 判断当前频道是否为启用状态
        if (wmchannel.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"当前频道状态为启用状态，不能删除");
        }

        // 根据id删除频道数据
        this.removeById(id);

        return ResponseResult.okResult("删除频道数据成功");
    }
}
